package cn.jiyun.util;

import org.springframework.stereotype.Component;
import java.util.Base64;

import java.io.*;
@Component
public class Base64Utils {
    /**
     * 图片转化成base64字符串
     * @param imgPath
     * @return
     */
    public static String getImageStr(String imgPath) {
        try (FileInputStream in = new FileInputStream(imgPath)) {
            byte[] data = in.readAllBytes();
            return Base64.getEncoder().encodeToString(data);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * base64字符串转化成图片
     *
     * @param imgData
     *            图片编码
     * @param imgFilePath
     *            存放到本地路径
     * @return
     * @throws IOException
     */
    @SuppressWarnings("finally")
    public static boolean generateImage(String imgData, String imgFilePath) throws IOException {
        if (imgData == null) {
            return false;
        }

        byte[] b = Base64.getDecoder().decode(imgData);

        try (FileOutputStream out = new FileOutputStream(imgFilePath)) {
            out.write(b);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }
}
